<template>
  <div class="camera-list">
    <div class="panel-header">
      <h3 class="panel-title">摄像机列表</h3>
      <div class="panel-actions">
        <el-button size="small" type="primary" @click="$emit('refresh')" :loading="loading">刷新</el-button>
        <el-button size="small" type="warning" @click="handleImport">还原</el-button>
        <el-button size="small" type="info" @click="handleExport">备份</el-button>
        <el-button size="small" type="success" @click="$emit('open-group-management')">
          分组管理
        </el-button>
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索摄像机名称"
        clearable
        @input="handleSearch"
        @clear="handleClearSearch"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!hasSelectedCameras">批量删除</el-button>
    </div>

    <div class="table-container">
      <ElementTable :table-title="tableColumns" :data="cameraList" :loading="loading" :show-pagination="true"
        :page-config="pageConfig" @select-change="handleSelectChange">
        <template #status="{ data }">
          <span class="status-text" :class="data.row.status === 1 ? 'online' : 'offline'">
            {{ data.row.status === 1 ? '在线' : '离线' }}
          </span>
        </template>
        <template #ptz="{ data }">
          <span class="status-text" :class="data.row.ptzEnable ? 'enabled' : 'disabled'">
            {{ data.row.ptzEnable ? '可控' : '非可控' }}
          </span>
        </template>
        <template #location="{ data }">
          <span class="status-text" :class="data.row.latitude && data.row.longitude ? 'marked' : 'unmarked'">
            {{ data.row.latitude && data.row.longitude ? '已标记' : '未标记' }}
          </span>
        </template>
      </ElementTable>
    </div>

    <!-- 文件上传组件 -->
    <input ref="fileInputRef" type="file" accept=".xlsx,.xls,.csv" style="display: none" @change="handleFileChange" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElButton, ElInput, ElIcon } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import ElementTable from '@/components/ElementTable/index.vue'
import { $importDevices, $exportDeviceList } from '@/api/device'
import { ExportUtil } from '@/utils/export'
import { confirm } from '@/utils/confirm'
import { success, error } from '@/utils/toast'
import type { Device } from '@/types'

// Props
interface Props {
  cameraList: Device[]
  selectedCameras: number[]
  loading: boolean
  hasSelectedCameras: boolean
  pageConfig: any
  keyword?: string
}

const props = defineProps<Props>()

// 文件输入引用
const fileInputRef = ref<HTMLInputElement>()

// 搜索关键词
const searchKeyword = ref(props.keyword || '')

// Emits
const emit = defineEmits<{
  'refresh': []
  'open-group-management': []
  'batch-delete': [cameraIds: number[]]
  'toggle-camera-selection': [cameraId: number]
  'select-change': [selectedCameras: number[]]
  'play-camera': [camera: Device]
  'search': [keyword: string]
}>()

// 监听外部keyword变化
watch(() => props.keyword, (newKeyword) => {
  searchKeyword.value = newKeyword || ''
})

// 表格列配置
const tableColumns = computed(() => [
  {
    type: 'selection',
    width: 50
  },
  {
    type: 'text',
    label: '摄像机名称',
    prop: 'name',
    width: 200,
    showOverflowTooltip: true
  },
  {
    type: 'text',
    label: 'IP地址',
    prop: 'ip',
    showOverflowTooltip: true
  },
  {
    type: 'text',
    label: '端口',
    prop: 'port',
    width: 80
  },
  {
    type: 'custom',
    label: '状态',
    prop: 'status',
    width: 100,
    name: 'status',
  },
  {
    type: 'custom',
    label: '可控云台',
    prop: 'ptzEnable',
    width: 100,
    name: 'ptz',
  },
  {
    type: 'custom',
    label: '标记',
    prop: 'location',
    width: 100,
    name: 'location',
  },
  {
    type: 'operate',
    label: '操作',
    width: 120,
    actions: [
      {
        name: '播放',
        type: 'primary',
        size: 'small',
        isLink: true,
        click: (row: Device) => handlePlay(row)
      }
    ]
  }
])

// 处理选择变化
const handleSelectChange = (selectedRows: any[]) => {
  const selectedIds = selectedRows.map(row => row.id)
  emit('select-change', selectedIds)
}

// 处理播放
const handlePlay = (camera: Device) => {
  emit('play-camera', camera)
}

// 处理搜索
const handleSearch = (value: string) => {
  emit('search', value)
}

// 处理清除搜索
const handleClearSearch = () => {
  emit('search', '')
}

// 处理导入
const handleImport = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  try {
    await confirm.confirm('确定要导入设备数据吗？', '导入设备')
    
    const response = await $importDevices(file)
    
    if (response.data) {
      const { success: successCount, failed: failedCount, errors } = response.data
      let message = `导入完成！成功：${successCount}条`
      if (failedCount > 0) {
        message += `，失败：${failedCount}条`
      }
      success(message)
      
      if (errors && errors.length > 0) {
        console.warn('导入错误详情:', errors)
      }
      
      // 刷新列表
      emit('refresh')
    }
  } catch (err) {
    if (err !== 'cancel') {
      error('导入失败')
    }
  } finally {
    target.value = ''
  }
}

// 处理导出
const handleExport = async () => {
  try {
    const response = await $exportDeviceList()
    ExportUtil.handleApiResponse(response, {
      filename: ExportUtil.generateFilename('设备数据'),
      fileType: 'csv'
    })
    success('导出成功')
  } catch (err) {
    error('导出失败')
  }
}

// 处理批量删除
const handleBatchDelete = () => {
  if (props.selectedCameras.length === 0) {
    error('请先选择要删除的摄像机')
    return
  }
  
  emit('batch-delete', props.selectedCameras)
}
</script>

<style scoped>
.camera-list {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f5f7fa;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.panel-actions {
  display: flex;
  gap: 8px;
}

.search-container {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 100%;
  max-width: 300px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.status-text {
  cursor: text;
  text-decoration: none;
}

.status-text.online {
  color: #67c23a;
}

.status-text.offline {
  color: #f56c6c;
}

.status-text.enabled {
  color: #67c23a;
}

.status-text.disabled {
  color: #f56c6c;
}

.status-text.marked {
  color: #67c23a;
}

.status-text.unmarked {
  color: #909399;
}
</style>
